package com.rdc.qingkou.presenter;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;

import com.rdc.qingkou.base.BasePresenterImpl;
import com.rdc.qingkou.contract.RecordContract;
import com.rdc.qingkou.ui.RecordDialogActivity;

import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.Timer;
import java.util.TimerTask;

import static com.rdc.qingkou.Application.MyApplication.getContext;


public class RecordPresenter extends BasePresenterImpl<RecordContract.View> implements RecordContract.PresenterI {
    private Timer timer;
    private int mTime = 0;
    private MediaPlayer mMediapalyer;
    private MediaRecorder mMediaRecorder = new MediaRecorder();
    private File audioFile;
    private TimerTask task;
    private Bundle bundle = new Bundle();
    private Message message = new Message();

    private String mFilePath = "";
    private Handler mHandler;

    private static final String TAG = "RecordPresenter";

    @Override
    public void play() {

        if (mMediaRecorder != null) {
            mMediaRecorder.reset();
        }
        if (audioFile != null && audioFile.exists()) {
            try {
                mMediapalyer = new MediaPlayer();
                mMediapalyer.setDataSource(audioFile.toString());
                mMediapalyer.prepare();
                mMediapalyer.start();
                mView.setRecord("正在播放");
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    @Override
    public String rerord() {

        mHandler = new RecordHandler((RecordDialogActivity) mView);


        try {
            if (ContextCompat.checkSelfPermission(getContext(),
                    Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions((Activity) mView,
                        new String[]{Manifest.permission.RECORD_AUDIO}, 1);
            } else {
                mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
                mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
                audioFile = new File(Environment.getExternalStorageDirectory().getCanonicalPath() + "/sound.amr");
                mMediaRecorder.setOutputFile(audioFile.getAbsolutePath());
                mMediaRecorder.prepare();
                mMediaRecorder.start();
                mView.setRecord("正在录音...");
            }
            mTime = 0;
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {

                    if (mTime > 120) {
                        this.cancel();
                        timer.cancel();
                        stop();
                    } else {
                        bundle.clear();
                        bundle.putInt("time", mTime * 1000);
                        message = new Message();
                        message.setData(bundle);
                        mHandler.sendMessage(message);
                    }
                    mTime++;
                }
            }, 0, 1000);


        } catch (IOException e) {
            e.printStackTrace();
        }
        if (audioFile != null) {
            mFilePath = audioFile.toString();
        }
        return mFilePath;
    }


    @Override
    public void stop() {
        if (audioFile != null && audioFile.exists()) {
            if (mMediaRecorder != null) {
                mMediaRecorder.reset();
            }
            if (timer != null) {
                timer.cancel();
                timer = null;
            }
        }
    }

    @Override
    public void cancel() {
        audioFile = null;
        mMediaRecorder.reset();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        mView.setRecord("点击录音");
        mView.setProgressBar(0);
    }


    private static class RecordHandler extends Handler {
        private final WeakReference<RecordDialogActivity> mActivity;

        public RecordHandler(RecordDialogActivity view) {
            mActivity = new WeakReference<RecordDialogActivity>(view);
        }


        @Override
        public void handleMessage(Message msg) {
            RecordDialogActivity mView = mActivity.get();
            if (mView != null) {
                mView.setProgressBar(msg.getData().getInt("time"));
            }
        }
    }
}
